package com.zima.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zima.mall.entity.*;
import com.zima.mall.mapper.*;
import com.zima.mall.service.UserService;
import com.zima.mall.util.MD5Utils;
import com.zima.mall.vo.BuyVo;
import com.zima.mall.vo.CartVo;
import com.zima.mall.vo.TableVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private LoginInformationMapper loginInformationMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private CartMapper cartMapper;

    @Resource
    private ProductsMapper productsMapper;

    @Override
    public String findByAccount(String account) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",account);

        MallUser mallUser = loginInformationMapper.selectOne(wrapper);

        return mallUser.getName();
    }

    @Override
    public TableVo findAllAverageUsers(Integer page,Integer size) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("role",1);//查找普通用户

        IPage mallUsersPage = new Page(page,size);
        IPage result =  loginInformationMapper.selectPage(mallUsersPage,wrapper);

        TableVo tableVo = new TableVo();
        tableVo.setTotalNum(loginInformationMapper.selectCount(wrapper));
        tableVo.setData(result.getRecords());

        return tableVo;
    }

    @Override
    public float consumptionStatics(Integer uid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid",uid);
        wrapper.select("amount");
        List<MallOrder> mallOrders = ordersMapper.selectList(wrapper);
        float sum = 0;
        for (MallOrder a:mallOrders){
            sum += a.getAmount();
        }

        return sum;
    }

    @Override
    public TableVo findAddressByAccount(String account) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",account);
        MallUser mallUser = loginInformationMapper.selectOne(wrapper);

        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("user_id",mallUser.getUserId());
        TableVo tableVo = new TableVo();
        tableVo.setData(addressMapper.selectList(wrapper1));
        tableVo.setTotalNum(addressMapper.selectCount(wrapper1));

        return tableVo;
    }

    @Override
    public Integer order(BuyVo buyVo) {//下订单有四个步骤1、订单表中加一项 2、订单项目表中加N项 3、对应的商品库存数减少 4、删除购物车对应的项
        if (buyVo.getProductList().size() == 0) return 0;//未选商品
        for (CartVo a:buyVo.getProductList()){//先判断库存是否充足
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("id",a.getId());
            Integer goodsId = cartMapper.selectOne(wrapper).getProductId();
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id",goodsId);
            if (productsMapper.selectOne(updateWrapper).getStock() < a.getQuantity()) return 0;//库存不足
        }

        Long orderNo = (long) (Math.random()*1000000000);//生成订单号

        MallOrder mallOrder = new MallOrder();//1、订单表中加一项
        mallOrder.setOrderNo(orderNo);
        mallOrder.setUid(buyVo.getProductList().get(0).getUserId());
        mallOrder.setAddrId(buyVo.getAddrId());
        float amount  = 0;
        for (CartVo a:buyVo.getProductList()){
            amount += a.getPrice() * a.getQuantity();
        }
        mallOrder.setAmount(amount);
        mallOrder.setType(buyVo.getType());
        mallOrder.setFreight(0);
        mallOrder.setStatus(1);
        ordersMapper.insert(mallOrder);


        for (CartVo a:buyVo.getProductList()) {
            MallOrderItem mallOrderItem = new MallOrderItem();
            mallOrderItem.setUid(buyVo.getProductList().get(0).getUserId());//2、订单项目表中加一项
            mallOrderItem.setTotalPrice(a.getPrice()*a.getQuantity());
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("id",a.getId());
            Integer goodsId = cartMapper.selectOne(wrapper).getProductId();
            mallOrderItem.setGoodsId(goodsId);
            mallOrderItem.setOrderNo(orderNo);
            mallOrderItem.setPrice(a.getPrice());
            mallOrderItem.setQuantity(a.getQuantity());
            orderItemMapper.insert(mallOrderItem);


            UpdateWrapper updateWrapper = new UpdateWrapper();//3、对应的商品库存数减少
            updateWrapper.eq("id",goodsId);
            updateWrapper.set("stock",productsMapper.selectOne(updateWrapper).getStock() - a.getQuantity());
            productsMapper.update(null,updateWrapper);

            cartMapper.delete(wrapper);//4.删除购物车对应的项
        }
        return 1;
    }

    @Override
    public Integer register(MallUser mallUser) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",mallUser.getAccount());
        if (loginInformationMapper.selectOne(wrapper) != null){//该用户名已存在
            return 0;
        }
        mallUser.setPassword(MD5Utils.inputPassToFormPass(mallUser.getPassword()));
        loginInformationMapper.insert(mallUser);
        return 1;
    }

    @Override
    public TableVo getUserInfo(String account) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",account);

        MallUser mallUser = loginInformationMapper.selectOne(wrapper);
        List<MallUser> mallUserList = new ArrayList<>();
        mallUserList.add(mallUser);
        TableVo tableVo = new TableVo();
        tableVo.setData(mallUserList);
        tableVo.setTotalNum(1);
        return tableVo;
    }

    @Override
    public Integer editUser(MallUser mallUser) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",mallUser.getUserId());
        int num = 0;
        num = loginInformationMapper.update(mallUser,updateWrapper);
        return num;
    }

    @Override
    public Integer delAddress(Integer id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id",id);
        int num = 0;
        num = addressMapper.delete(wrapper);
        return num;
    }

    @Override
    public Integer addAddress(Address address,String account) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",account);
        address.setUserId(loginInformationMapper.selectOne(wrapper).getUserId());
        int num = 0;
        num = addressMapper.insert(address);
        return num;
    }

    @Override
    public Integer editAddress(Address address) {
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",address.getId());
        int num = 0;
        num = addressMapper.update(address,wrapper);
        return num;
    }


}
